package com.zhongkun.datahome.web.rest;

import com.zhongkun.datahome.common.annotation.Log;
import com.zhongkun.datahome.common.core.domain.R;
import com.zhongkun.datahome.common.enums.BusinessType;
import com.zhongkun.datahome.service.req.qry.file.DownloadBody;
import com.zhongkun.datahome.service.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: lifengsheng
 * @Date: 2025/4/18 09:35
 * @Desc
 */
@Api("文件管理")
@RestController
@RequestMapping("/core/commonFile")
public class CommonFileController {
    private static final Logger log = LoggerFactory.getLogger(CommonFileController.class);

    @Resource
    private IFileService fileService;

    @ApiOperation("上传文件")
    @PreAuthorize("@ss.hasPermi('core:commonFile:upload')")
    @Log(title = "文件管理", businessType = BusinessType.UPLOAD)
    @PostMapping("/upload")
    public R<String> upload(@RequestBody MultipartFile file) {
        try {
            String url = fileService.upload(file);
            log.info("commonFile upload file success, url: {}", url);
            return R.ok(url);
        } catch (Exception e) {
            log.error("commonFile upload file failed, ", e);
            e.printStackTrace();
        }
        return R.fail();
    }

    @ApiOperation("获取文件大小")
    @PreAuthorize("@ss.hasPermi('core:commonFile:size')")
    @GetMapping("/size")
    public R<String> getSize(String url) {
        return R.ok(fileService.getFileSize(url));
    }

    @ApiOperation("根据url下载文件")
    @PreAuthorize("@ss.hasPermi('core:commonFile:download')")
    @Log(title = "文件管理", businessType = BusinessType.DOWNLOAD)
    @PostMapping(value = "/download")
    public R<Void> download(HttpServletResponse response, @RequestBody DownloadBody body) {
        fileService.download(response, body);
        return R.ok();
    }
}
